import { defineStore } from 'pinia';
import { ref } from 'vue';
import { request } from '@/utils/request';
import { getCache, setCache } from '@/utils/cache';
interface selectFace {
	label: string | any;
	value: string | any;
	id: string | any;
	describes: string | any;
}
export const dictionaryStores = defineStore('dictionary', () => {
	let dictionaryData = ref(
		getCache('dictionary')
	);
	let netWork = false;
	const hasDict = (type: any) => {
		if (!dictionaryData.value.hasOwnProperty(type)) {
			getAll(() => {
				setTimeout(function () {
					// 页面重载
					const pages = getCurrentPages();
					// 声明一个pages使用getCurrentPages方法
					const curPage: any = pages[pages.length - 1];
					// 声明一个当前页面
					curPage.onLoad(curPage.options); // 传入参数
					curPage.onShow();
					curPage.onReady();
					// 执行刷新
				}, 500);
			});
		}
	};
	// 静态获取 根据字典值，获取字典名称
	const getText = (type: any, value: any): string => {
		hasDict(type);
		if ([null, undefined, ''].includes(value)) {
			return '';
		}
		let list: any = dictionaryData.value[type];
		let item: any = list?.find((a: any) => a.value == value);
		return item?.label || '';
	};
	// 静态获取 根据字典值，获取字典对象
	const getValue = (type: any, value: any): selectFace | any => {
		hasDict(type);
		if ([null, undefined, ''].includes(value)) {
			return {};
		}
		let list: any = dictionaryData.value[type];
		let item: any = list?.find((a: any) => a.value == value);
		return item || {};
	};

	// 静态获取 根据下标值，获取字典对象
	const getObject = (type: any, index: any): selectFace | any => {
		hasDict(type);
		let list: any = dictionaryData.value[type];
		return list[index] || {};
	};

	// 静态获取 根据字典类型，获取字典列表
	const getList = (type: any): Array<any> => {
		hasDict(type);
		return dictionaryData.value[type] || [];
	};

	// 获取所有字典列表
	const getAll = async (typeList:any,callback?: any): Promise<any> => {
		if (netWork) {
			return;
		}
		netWork = true;
		request({
			url: '/api/patient/dataDictionary/getDataDictionary',
			method: 'POST',
			data: {
				typeList: typeList
			}
		}).then((res: any) => {
			console.log(res,'aaadd')
			res.data.forEach((item: any) => {
				dictionaryData.value[item.type] = initEnum(item.children);
			});
			setCache('dictionary', dictionaryData.value);
			callback && callback(dictionaryData.value);
			netWork = false;
		});
	};

	// 字典递归
	const initEnum = (jsonList: any[]): Array<selectFace> => {
		let list: Array<selectFace> = [];
		if (!jsonList) {
			return list;
		}
		jsonList.forEach((item) => {
			if (item.children?.length > 0) {
				list = list.concat(initEnum(item.children));
			} else {
				list.push({
					label: item.name,
					value: item.dataValue,
					id: item.id,
					describes: item.describes
				});
			}
		});
		return list;
	};

	return {
		getAll,
		getText,
		getList,
		getObject,
		getValue
	};
});
